<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>深拷贝</title>
</head>
<body>
<a href="https://www.lodashjs.com/docs/lodash.cloneDeep">lodash深拷贝</a>
<script>
const deepClone = obj => {
	return clone(obj)
}

// 类型的判断
const isType = (obj, type) => {
	if (typeof obj !== 'object') return false;
	// 判断数据类型的经典方法：
	const typeString = Object.prototype.toString.call(obj);
  	let flag;
	switch (type) {
		case 'Array':
		    flag = typeString === '[object Array]';
		break;
		case 'Date':
		    flag = typeString === '[object Date]';
		break;
		case 'RegExp':
		    flag = typeString === '[object RegExp]';
		break;
		default:
	      	flag = false;
	}
	return flag;
}
/**
* deep clone
* @param  {[type]} parent object 需要进行克隆的对象
* @return {[type]}        深克隆后的对象
*/
const clone = parent => {
	// console.log(parent)
	if (parent === null) return null
	if (typeof parent !== 'object') return parent;

    let child, proto
	if (isType(parent, 'Array')) {
		// 对数组做特殊处理
	    child = []
    } else if (isType(parent, 'RegExp')) {
		// 对正则对象做特殊处理
      	child = new RegExp(parent.source, getRegExp(parent))
		if (parent.lastIndex) child.lastIndex = parent.lastIndex
    } else if (isType(parent, 'Date')) {
		// 对Date对象做特殊处理
      	child = new Date(parent.getTime())
    } else {
		// 处理对象原型
      	proto = Object.getPrototypeOf(parent)
		// 利用Object.create切断原型链
      	child = Object.create(proto)
    }
	for (const i in parent) {
		// 递归查找
		// 递归主要是用了闭包的特性，延申了变量的作用域
		// 当parent[i]是个object时，child[i] = parent[i]遍历返回的child
      	child[i] = clone(parent[i])
      	// console.log(i, child[i])
    }
	return child
}
var obj = { 
  name: '张三',
  age: 23, 
  obj: { name: '李四', age: 46},
  date: new Date(),
  arr:[1,2,3]
}

var newObj = deepClone(obj)
console.log(newObj)
</script>
</body>
</html>